package org.jeecg.modules.register.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.Md5Util;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.register.entity.SubjectLegal;
import org.jeecg.modules.register.mapper.SubjectLegalMapper;
import org.jeecg.modules.register.mapper.SubjectMemberLevelMapper;
import org.jeecg.modules.register.service.ISubjectLegalService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Description: subject_legal
 * @Author: jeecg-boot
 * @Date:   2024-09-20
 * @Version: V1.0
 */
@Service
public class SubjectLegalServiceImpl extends ServiceImpl<SubjectLegalMapper, SubjectLegal> implements ISubjectLegalService {

    @Resource
    private SubjectLegalMapper subjectLegalMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Resource
    private SubjectMemberLevelMapper subjectMemberLevelMapper;

    @Autowired
    private BaseCommonService baseCommonService;

    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private ISysUserService userService;

    @Override
    public Result<SubjectLegal> registe(SubjectLegal subjectLegal) {

        //验证验证码是否正确
        String captcha = subjectLegal.getCheckCode();
        String checkKey = subjectLegal.getCheckKey();
        if(captcha==null){
            return Result.error("验证码无效");
        }
        String lowerCaseCaptcha = captcha.toLowerCase();
        String realKey = Md5Util.md5Encode(lowerCaseCaptcha+checkKey, "utf-8");
        Object checkCode = redisUtil.get(realKey);
        if(checkCode==null || !checkCode.equals(lowerCaseCaptcha)) {
            return Result.error("验证码错误");
        }


        if(null == subjectLegal.getSubjectId() ){
            QueryWrapper<SubjectLegal> queryWrapper = new QueryWrapper<SubjectLegal>();
            queryWrapper.eq(StringUtils.isNotEmpty(subjectLegal.getLegalCode()),"legal_code", subjectLegal.getLegalCode());

            List<SubjectLegal> list = subjectLegalMapper.selectList(queryWrapper);
            if(list.size() > 0){
                return Result.error("法人主体已经注册，请登陆之后再完成注册信息填写！");
            }

            SysUser user = trunUserBySubjectLegal(subjectLegal);
            user.setIsRegister(1);
            //管理员账号信息插入
            if(!addSysUserInfo(user)){
                return Result.error("注册失败，请联系管理员！");
            }

            subjectLegal.setRegistStep(1);
            subjectLegal.setSysUserId(user.getId());
            subjectLegalMapper.insert(subjectLegal);

            SubjectLegal subjectLegalNew = subjectLegalMapper.selectOne(queryWrapper);
            subjectLegalNew.setCurrentStep(2);
            //登陆返回token
            String token = JwtUtil.sign(user.getUsername(), user.getPassword());
            // 设置token缓存有效时间
            redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
            redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);
            subjectLegalNew.setToken(token);

            subjectLegalNew.setCurrentStep(2);
            return Result.ok(subjectLegalNew);
        }else{
            QueryWrapper<SubjectLegal> queryWrapper = new QueryWrapper<SubjectLegal>();
            queryWrapper.eq("subject_id", subjectLegal.getSubjectId());


            List<SubjectLegal> list = subjectLegalMapper.selectList(queryWrapper);
            if(list.size() == 1){
                subjectLegalMapper.updateById(subjectLegal);
            }


            SubjectLegal subjectLegalNew = subjectLegalMapper.selectOne(queryWrapper);
            subjectLegalNew.setCurrentStep(2);
            return Result.ok(subjectLegalNew);
        }

    }

    private SysUser trunUserBySubjectLegal(SubjectLegal subjectLegal){
        SysUser user = new SysUser();

        if(1 == subjectLegal.getSubjectType()){
            user.setUsername(subjectLegal.getLegalCode());
            user.setRealname(subjectLegal.getLegalName());
        }else{
            user.setUsername(subjectLegal.getAdminLogin());
            user.setRealname(subjectLegal.getAdminUser());
        }

        user.setPassword(subjectLegal.getAdminPassword());
        user.setPhone(subjectLegal.getAdminPhone());
        user.setTelephone(subjectLegal.getAdminTel());
        if(StringUtils.isNotBlank(subjectLegal.getAdminSex())){
            if(subjectLegal.getAdminSex().equals("1")){
                user.setSex(1);
            }else{
                user.setSex(2);
            }
        }

        user.setUserSource(CommonConstant.USER_SOURCE_4);// 会员注册

        return user;
    }

    private boolean addSysUserInfo(SysUser user) {

        String selectedRoles = "1842001826549686274,1842001826549687657";
        String selectedDeparts = "";

        try {
            //先查询 用户是否存在
            SysUser old = sysUserService.getUserByName(user.getUsername());
            if(null == old){
                user.setCreateTime(new Date());//设置创建时间
                String salt = oConvertUtils.randomGen(8);
                user.setSalt(salt);
                String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
                user.setPassword(passwordEncode);
                user.setStatus(1);
                user.setIsRegister(1);
                user.setDelFlag(CommonConstant.DEL_FLAG_0);
                //用户表字段org_code不能在这里设置他的值
                user.setOrgCode(null);
                // 保存用户走一个service 保证事务
                sysUserService.saveUser(user, selectedRoles, selectedDeparts);
                baseCommonService.addLog("会员注册，username： " + user.getUsername(), CommonConstant.LOG_TYPE_2, 2);
            }else{
                old.setUsername(user.getUsername());
                String salt = oConvertUtils.randomGen(8);
                old.setSalt(salt);
                String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
                old.setPassword(passwordEncode);
                old.setRealname(user.getRealname());
                old.setIsRegister(1);
                old.setPhone(user.getPhone());
                old.setTelephone(user.getTelephone());
                old.setUserSource(CommonConstant.USER_SOURCE_4);// 会员注册
                user.setId(old.getId());

                sysUserService.editUser(user, selectedRoles, selectedDeparts);
                baseCommonService.addLog("会员注册，username： " + user.getUsername(), CommonConstant.LOG_TYPE_2, 2);
            }

        } catch (Exception e){
            log.error(e.getMessage(), e);
            return false;
        }
        return true;

    }


    @Override
    public Result<SubjectLegal> registNext(SubjectLegal subjectLegal) {

        if(null == subjectLegal.getSubjectId()){
            return Result.error("登陆信息还没有录入，请先完成登录信息注册！");
        }

        if(subjectLegal.getCurrentStep() > subjectLegal.getRegistStep()){
            subjectLegal.setRegistStep(subjectLegal.getCurrentStep());
            subjectLegal.setCurrentStep(subjectLegal.getCurrentStep()+1);
        }

        QueryWrapper<SubjectLegal> queryWrapper = new QueryWrapper<SubjectLegal>();
        queryWrapper.eq(StringUtils.isNotEmpty(subjectLegal.getLegalCode()),"legal_code", subjectLegal.getLegalCode());
        SubjectLegal old = new SubjectLegal();
        List<SubjectLegal> list = subjectLegalMapper.selectList(queryWrapper);
        if(list.size() == 1){
            old = list.get(0);
        }
        //注册完成
        if(subjectLegal.getRegistStep() >= 10){

            //等级为空 说明是第一次注册完成
            if(StringUtils.isEmpty(old.getMemberLevel())){
                subjectLegal.setMemberLevel("1");
                subjectLegal.setMemberState("2");
                if(subjectMemberLevelMapper.selectMemberCountByCode(subjectLegal) == 0){
                    subjectMemberLevelMapper.insertMerberLevel(subjectLegal);
                }
            }


            //当前用户已经绑定过CA 绑定过数据状态直接注册完成；
            SysUser sysUser = userService.getUserByName(subjectLegal.getLegalCode());
            if(1 == sysUser.getIsCa()){
                subjectLegal.setIsCa(sysUser.getIsCa());
                subjectLegal.setCasCode(sysUser.getCasCode());
                subjectLegalMapper.updateLagelCasInfo(subjectLegal);
                subjectLegalMapper.updateSysUserRegistState(subjectLegal);
            }
        }

        subjectLegalMapper.updateById(subjectLegal);

        QueryWrapper<SubjectLegal> queryWrapper1 = new QueryWrapper<SubjectLegal>();
        queryWrapper1.eq(null != subjectLegal.getSubjectId(),"subject_id",subjectLegal.getSubjectId());

        SubjectLegal subjectLegalNew = subjectLegalMapper.selectOne(queryWrapper1);

        return Result.ok(subjectLegalNew);
    }

    @Override
    public Result queryByInfo(SubjectLegal subjectLegal) {

//        if(null == subjectLegal.getSubjectId()){
//            return Result.error("登陆信息还没有录入，请先完成登录信息注册！");
//        }

        QueryWrapper<SubjectLegal> queryWrapper = new QueryWrapper<SubjectLegal>();
        queryWrapper.eq(null != subjectLegal.getLegalCode(), "legal_code",subjectLegal.getLegalCode());
        queryWrapper.eq(null != subjectLegal.getSubjectId(),"subject_id",subjectLegal.getSubjectId());
        queryWrapper.eq(null != subjectLegal.getSysUserId(),"sys_user_id",subjectLegal.getSysUserId());

        SubjectLegal subjectLegalNew = subjectLegalMapper.selectOne(queryWrapper);
        if(subjectLegalNew == null){
            return Result.error("法人主体信息不存在，请先完成注册！");
        }
        subjectLegalNew.setCurrentStep(subjectLegal.getCurrentStep());

        return Result.ok(subjectLegalNew);
    }

    @Override
    public Result<SubjectLegal> registUp(SubjectLegal subjectLegal) {
        if(null == subjectLegal.getSubjectId()){
            return Result.error("登陆信息还没有录入，请先完成登录信息注册！");
        }

        QueryWrapper<SubjectLegal> queryWrapper = new QueryWrapper<SubjectLegal>();
        queryWrapper.eq(null != subjectLegal.getLegalCode(), "legal_code",subjectLegal.getLegalCode());
        queryWrapper.eq(null != subjectLegal.getSubjectId(),"subject_id",subjectLegal.getSubjectId());
        queryWrapper.eq(null != subjectLegal.getSysUserId(),"sys_user_id",subjectLegal.getSysUserId());

        SubjectLegal subjectLegalNew = subjectLegalMapper.selectOne(queryWrapper);
        if(subjectLegalNew == null){
            return Result.error("法人主体信息不存在，请先完成注册！");
        }
        subjectLegalNew.setCurrentStep(subjectLegal.getCurrentStep());
        subjectLegalNew.setCurrentStep(subjectLegalNew.getCurrentStep() -1);
        return Result.ok(subjectLegalNew);
    }

    @Override
    public Result<SubjectLegal> updateCasInfo(SubjectLegal subjectLegal) {
        if(null == subjectLegal.getSubjectId()){
            return Result.error("登陆信息还没有录入，请先完成登录信息注册！");
        }

        if(StringUtils.isEmpty(subjectLegal.getCasCode())){
            return Result.error("CAS编码不能为空！");
        }
        subjectLegalMapper.updateLagelCasInfo(subjectLegal);
        return Result.ok(subjectLegal);
    }
}
